#!/bin/bash
#pMusic
#GPL - Copyright Sigmund Berglund

export TEXTDOMAIN=pmusic
export OUTPUT_CHARSET=UTF-8

case "$1" in
-play_direct)
	SOURCE=${2#[0-9]*:}; SOURCE=${SOURCE#[0-9]* }
	echo 0 > $WORKDIR/SS
	$APPDIR/func_player -stop -skip_update
	$APPDIR/func_player -playing "$SOURCE" play_direct &
	;;
-playqueue_change) #call from multiple playqueue tab
	NEW_TAB=${2}
	read OLD_TAB < $WORKDIR/PLAYLIST_X
	cp -f $WORKDIR/playlist $WORKDIR/playlist_$OLD_TAB
	echo ${NEW_TAB} > $WORKDIR/PLAYLIST_X #active playqueue
	[ ! -f $WORKDIR/playlist_${NEW_TAB} ] && echo -n > $WORKDIR/playlist_${NEW_TAB}
	cp -f $WORKDIR/playlist_${NEW_TAB} $WORKDIR/playlist
	#switch icon
	cp -f $APPDIR/themes/$THEME/blank.svg $WORKDIR/PLAYLIST_${OLD_TAB}_ICON.svg
	cp -f $APPDIR/themes/$THEME/icon_playqueue_marker.svg $WORKDIR/PLAYLIST_${NEW_TAB}_ICON.svg
	;;
-export_playqueue) #call from menu in main gui
	if [ "`LC_ALL=C grep -F pmusic <<< "$(LC_ALL=C ps -eo pid,command)" | grep -F func_export`" ]; then #already running --> add to list
		cut -d"|" -f4 $WORKDIR/playlist >> $WORKDIR/exportlist
	else
		$APPDIR/func_export &
		sleep 0.1
		cut -d"|" -f4 $WORKDIR/playlist > $WORKDIR/exportlist
	fi
	;;
-youtube_msg) #show msg in main gui
	NAME=''
	for I in `seq 0 9`; do
		IFS='|' read NAME ADR < $HOME/.pmusic/nowplaying
		[[ "$NAME" && "$ADR" = *youtube.com* ]] && break
		sleep 1
	done
	echo "${STORAGE_DIR}/youtube/${NAME}.m4a" > $WORKDIR/YOUTUBE_OUTFILE #why m4a? see: http://superuser.com/questions/349518/how-to-use-ffmpeg-to-add-metadata-to-an-aac-file-without-reencoding
	echo 3 > $WORKDIR/maingui_notebook_page
	echo true > $WORKDIR/UPDATE_GUI
	;;
-youtube_download)
	YOUTUBE_OUTFILE="$2"
	#check if already exist
	if [ -s "${YOUTUBE_OUTFILE}" ]; then
		IMG=dialog-warning
		FRAME="$(gettext 'Warning')"
		TXT1="<b>${YOUTUBE_OUTFILE} $(gettext 'already exist')</b>"
		TXT2="$(gettext 'Do you want to overwrite existing file?')"
		DEFAULT=no
		. $APPDIR/box_yesno
		[ $EXIT = no ] && exit
	fi
	#get adress
	IFS='|' read NAME ADR < $HOME/.pmusic/nowplaying
	NAME=${YOUTUBE_OUTFILE##*/}; NAME=${NAME%.*} #$YOUTUBE_OUTFILE holds edited name - better than $NAME in $HOME/.pmusic/nowplaying
	#update in case user has changed name
	echo "${NAME}|${ADR}" > $HOME/.pmusic/nowplaying
	$APPDIR/func_svg -nowplaying "$NAME"
	#hide msg
	echo 0 > $WORKDIR/maingui_notebook_page
	echo true > $WORKDIR/UPDATE_GUI
	#download
	if [ "$(which youtube-dl)" ]; then
		youtube-dl -x -o "${YOUTUBE_OUTFILE}" $ADR
	else #does not work post sept 2017 because of lack of permission
		TMP=$(wget -O - -t 3 -U "$USERAGENT" --referer="http://www.google.com" http://keepvid.com/?url=${ADR} | sed 's/http/\nhttp/g' | grep -F 'itag=140')
		wget -O "${YOUTUBE_OUTFILE}" -t 3 -U "$USERAGENT" $TMP
	fi
	#set metatags
	if [[ "$NAME" = *' - '* ]]; then
		ARTIST=${NAME%% - *}
		TITLE=${NAME##* - }
		#add to db
		( flock -e 200
			echo "${YOUTUBE_OUTFILE}|$ARTIST|$TITLE||||||0|||||${YOUTUBE_OUTFILE}|gtk-audio||||||" >> "$STORAGE_DIR"/index_mymusic
		) 200>$WORKDIR/mymusic_db.lockfile
		#write tags
		. $APPDIR/func_id3io "${YOUTUBE_OUTFILE}" -write
	else
		( flock -e 200
			echo "${YOUTUBE_OUTFILE}|$NAME|||||||0|||||${YOUTUBE_OUTFILE}|gtk-audio||||||" >> "$STORAGE_DIR"/index_mymusic
		) 200>$WORKDIR/mymusic_db.lockfile
	fi
	;;
-dependency_check)
	info(){
		HEADING="$(gettext 'Dependency check')"
		IMG='info'
		FRAME="$(gettext 'info')"
		TXT1="$(gettext 'pMusic uses only the binary <b>cdda2wav</b> of the <b>Cdrtools</b> pack - For both playback and ripping audio-CD.

Note!
pMusic will work just fine even if missing all recommended and optional items.')"
		. $APPDIR/box_ok &
	}
	export -f info
	
	pmusic -D #to create textfile
	sed -i -e 's%OK%OK|gtk-yes%g' -e 's%MISSING%MISSING|gtk-no%g' $WORKDIR/dependencies
	$APPDIR/func_svg -heading "$(gettext 'Dependency check')" > /dev/null

	echo '
	<window title="pMusic - '$(gettext 'Dependency check')'" icon-name="pmusic" default_height="550" default_width="550">
	 <vbox space-expand="false" space-fill="false">
      <hbox spacing="0" height="80" scrollable="true" space-expand="true" space-fill="true" vscrollbar-policy="2" hscrollbar-policy="2">
	   <eventbox name="svgheading">
	    <hbox space-expand="true" space-fill="true">
	     <text width-request="20" space-expand="false" space-fill="false"><label>""</label></text>
	     <text ypad="40" use-markup="true" space-expand="false" space-fill="false"><label>"<i>'$(gettext 'Click an item to browse its homepage')'</i>"</label></text>
	     <text space-expand="true" space-fill="true"><label>""</label></text>
	     <hbox spacing="0" '$SF'>
	      <vbox>
	       <button relief="2" can-focus="false" space-expand="false" space-fill="false">
	        <input file stock="gtk-help"></input>
	        <action>info</action>
	       </button>
	       <text space-expand="true" space-fill="true"><label>""</label></text>
	      </vbox>
	     </hbox>
	    </hbox>
	   </eventbox>
	  </hbox>

	  <vbox space-expand="true" space-fill="true">
	   <tree headers_visible="false" column-visible="true|false|true" exported_column="1">
	    <variable>DEPCHK</variable>
	    <label>a|b|c|d|e|f|g</label> 
	    <input file stock-column="5">'$WORKDIR'/dependencies</input>
	    <action signal="button-release-event">export GTK2_RC_FILES='$HOME'/.gtkrc-2.0; '$BROWSER' "$DEPCHK"</action>
	   </tree>
	  </vbox>
	 </vbox>
	</window>' | gtkdialog -s &
	;;

-visualization)
	killall ffplay
	if [ "$2" ]; then
		CMD="`grep "^${2}|" $APPDIR/txt_visualization`"
	else
		read CMD < $WORKDIR/visualization_cmd #last used cmd
	fi
	CMD=${CMD#*|}
	[ ! "$CMD" ] && exit
	read TMP < $WORKDIR/visualization_fullscreen
	[ "$TMP" = "true" ] && FULLSCREEN='-fs' || FULLSCREEN='-sn' #-sn to have a value 
	echo "$CMD" > $WORKDIR/visualization_cmd #we need to know the last used cmd if switching fullscreen
	echo "ffplay -autoexit -window_title \"pMusic\" -an $FULLSCREEN -f lavfi $CMD 2> $WORKDIR/visualization_error &" > $WORKDIR/visualization_exec #for information: plugin backend_cmd
	ffplay -autoexit -window_title "pMusic" -an "$FULLSCREEN" -f lavfi "$CMD" 2> $WORKDIR/visualization_error &
	sleep 1
	if grep -F 'No such filter' $WORKDIR/visualization_error; then
		TMP="`grep -F 'No such filter' $WORKDIR/visualization_error | cut -d"'" -f2`"
		TXT1="<b>$(gettext 'Requested visualization filter is not supported.')</b>"
		TXT2="$(gettext 'ffmpeg installed on your system may be too old or compiled without this support.')

$(gettext 'Requested filter:') $TMP"
		. $APPDIR/box_ok
	fi
	;;

-check_playlist)
	FILE="$2"
	case "$FILE" in *pmu) TMP=4;; *pmd) TMP=1;; esac #set field to read
	#check if an update is require
	while read I; do
		case $I in /*) [ ! -f "$I" ] && C=1;; esac
	done <<< "$(cut -d'|' -f$TMP "$FILE")"
	[ "$C" != "1" ] && exit
	#we don't update lists outside the pMusic internal structure (pmd and album-pmu). If user has built his own lists we leave them even if not in shape --> pMusic will anyway search for alternative source when start playing. 
	case $FILE in
		"$STORAGE_DIR"*.pmu)	$APPDIR/func_index -update_pmu "$FILE";;
		*.pmd)					$APPDIR/func_index -update_pmd "$FILE";;
	esac
	;;

-playlist_collapse)
	IFS='|' read COMMAND ARTIST TITLE ALBUM NR YEAR GENRE COMMENT RATING FORMAT BITRATE LENGTH COL13 ADR ICON <<< "$(grep -Fm1 "${2}|" $WORKDIR/sourcelist)"
	[[ $COMMAND != pmusicbrowse_collapse:* ]] && exit
	SOURCELIST_PRE="`grep -B 1000 -F "pmusicbrowse_collapse:$ADR" $WORKDIR/sourcelist | grep -vF "pmusicbrowse_collapse:$ADR"`"
	SOURCELIST_POST="`grep -A 1000 -F "pmusicbrowse_collapse:$ADR" $WORKDIR/sourcelist | grep -vF "pmusicbrowse_collapse:$ADR"`"
	echo "$SOURCELIST_PRE" > $WORKDIR/sourcelist
	if [ "$ALBUM" ]; then #pmusic generated album list
		echo "pmusicbrowse_expand:$ADR|$ARTIST||$ALBUM||$YEAR||||||||$ADR|$ICON||||||" >> $WORKDIR/sourcelist
	else
		find "$ADR" -printf "pmusicbrowse_expand:%p|%f||||$YEAR||||||||%p|$ICON||||||\n" >> $WORKDIR/sourcelist
	fi
	#remove track-lines
	TMP=`grep -m1 -n '___________________________' <<< "$SOURCELIST_POST" | tail -n1`
	echo "$SOURCELIST_POST" | tac | head -n -${TMP%%:*} | tac >> $WORKDIR/sourcelist
	;;

-playlist_expand) #$2=file
	IFS='|' read COMMAND ARTIST TITLE ALBUM NR YEAR GENRE COMMENT RATING FORMAT BITRATE LENGTH COL13 ADR ICON <<< "$(grep -Fm1 "${2}|" $WORKDIR/sourcelist)"
	SOURCELIST_PRE="`grep -B 1000 -F "pmusicbrowse_expand:$ADR" $WORKDIR/sourcelist | grep -vF "pmusicbrowse_expand:$ADR"`"
	SOURCELIST_POST="`grep -A 1000 -F "pmusicbrowse_expand:$ADR" $WORKDIR/sourcelist | grep -vF "pmusicbrowse_expand:$ADR"`"
	echo "$SOURCELIST_PRE" > $WORKDIR/sourcelist
	case $ADR in
		*.pmd)
			$APPDIR/func -check_playlist "$ADR" #check if paths is valid
			find "$ADR" -printf "pmusicbrowse_collapse:%p|%f||||$YEAR||||||||%p|$ICON||||||\n" >> $WORKDIR/sourcelist
			echo -n > $WORKDIR/tmp_playlist_expand
			while read I; do
				IFS='|' read ADR2 ARTIST2 C <<< "${I}"
				[ ! "$ADR2" ] && ADR2="$ARTIST2" #in case no valid file (ie. after an update of favorite lists in the update_index function.) 
				case $I in *jamendo.com*) URL_JAMENDO="`echo "$I" | awk -F 'id=' '{print $2}' | awk -F '|' '{print $1}'`";; esac
				TMP="`grep -Fm1 "$ADR2" "$STORAGE_DIR/index_mymusic"`"
				if [ "$TMP" ]; then
					echo "$TMP" >> $WORKDIR/tmp_playlist_expand
				elif [ "$URL_JAMENDO" ]; then
					TMP="`grep -Fm1 "$URL_JAMENDO" "$STORAGE_DIR/index_jamendo"`"
					[ "$TMP" ] && echo "$TMP" >> $WORKDIR/tmp_playlist_expand || grep -Fm1 "$ADR2" "$ADR" >> $WORKDIR/tmp_playlist_expand
				else
					grep -Fm1 "$ADR2" "$ADR" >> $WORKDIR/tmp_playlist_expand
				fi
			done < "$ADR"
			$APPDIR/func_rating -buildlist 1 $WORKDIR/tmp_playlist_expand 0 0 "    " >> $WORKDIR/sourcelist #get rating
			;;
		*.pmu)
			$APPDIR/func -check_playlist "$ADR" #check if paths is valid
			if [ "$ALBUM" ]; then #pmusic generated album list
				echo "pmusicbrowse_collapse:$ADR|$ARTIST||$ALBUM||||$YEAR||||||$ADR|$ICON||||||" >> $WORKDIR/sourcelist
			else
				find "$ADR" -printf "pmusicbrowse_collapse:%p|%f||||$YEAR||||||||%p|$ICON||||||\n" >> $WORKDIR/sourcelist
			fi
			echo -n > $WORKDIR/tmp_playlist_expand
			while read I; do
				IFS='|' read ICON LENGTH NAME ADR ID <<< "$I"
				if [ -s "$ADR" ]; then
					grep -F "$ADR" "$STORAGE_DIR/index_mymusic" >> $WORKDIR/tmp_playlist_expand
				elif [[ "$ADR" = *jamendo.com* ]]; then
						ARTIST=${NAME%\ -\ *}
						TITLE=${NAME#*\ -\ }
						echo "$ADR|$ARTIST|$TITLE|||||||mp3|96|$LENGTH||$ADR|gtk-audio" >> $WORKDIR/tmp_playlist_expand
				else
					echo "$I" | awk -F'|' '{print $4 "|" $3 "||||||||||||" $4 "|gtk-audio_missing"}' >> $WORKDIR/tmp_playlist_expand
				fi
			done < "$ADR"
			$APPDIR/func_rating -buildlist 1 $WORKDIR/tmp_playlist_expand 0 0 "    " >> $WORKDIR/sourcelist #get rating
			;;
		*.m3u)
			find "$ADR" -printf "pmusicbrowse_collapse:%p|%f||||$YEAR||||||||%p|$ICON||||||\n" >> $WORKDIR/sourcelist
			while read I; do
				case $I in
					'#EXTM3U'*|'#M3U'*) #header info. We don't use this
						continue
						;;
					'#EXT'*) #we use #EXT info in m3u if available
						LENGTH=${I#*:}
						LENGTH=${LENGTH%%,*}
						[ "$LENGTH" -gt 0 ] || LENGTH='' && LENGTH=`$APPDIR/func_C -sec2time $LENGTH` #m3u stores length in seconds, we want a human readable length
						NAME=${I#*,}
						continue #if EXT line, go to next line...
						;;
				esac
				[ ! "$NAME" ] && NAME=${I##*/}
				#Adress (path/URL)
				case $I in
					cdda:*|*/*)	ADR="$I";;
					*) 			ADR="${SOURCE%/*}/$I";; #no path for files in list. Use current dir
				esac
				echo "$ADR|    $NAME||||||||||$LENGTH||$ADR|" | tr -d '\r' >> $WORKDIR/sourcelist
				NAME=""
			done < "$ADR"
			;;
		*.pls)
			find "$ADR" -printf "pmusicbrowse_collapse:%p|%f||||$YEAR||||||||%p|$ICON||||||\n" >> $WORKDIR/sourcelist
			while read I; do
				NR=${I%%=*}; NR=${NR#*e}
				ADR=${I#*=}
				#length
				LENGTH="`grep -F "Length${NR}=" "$SOURCE" | cut -d= -f2`"
				[ "$LENGTH" -gt 0 ] || LENGTH='' && LENGTH=`$APPDIR/func_C -sec2time $LENGTH` #pls stores length in seconds, we want a human readable length
				#---
				NAME="`grep -F "Title${NR}=" "$SOURCE" | cut -d= -f2`"
				[ ! "$NAME" ] && NAME=${ADR##*/}
				echo "$ADR|    $NAME||||||||||$LENGTH||$ADR|" | tr -d '\r' >> $WORKDIR/sourcelist
			done <<< "$(grep "^File" "$ADR")"
			;;
	esac
	echo 'pmusic_expand_end|___________________________' >> $WORKDIR/sourcelist
	echo "$SOURCELIST_POST" >> $WORKDIR/sourcelist
	;;

-browse)
	[[ "$PTR_BTN" = @"2|3" ]] && exit #right-click menu or play from sourcelist
	[ -f "${SOURCE}" ] && exit #see func_add
	case $SOURCE in 
		pmusicbrowse_search:*)
			SEARCH=${SOURCE#*:}
			$APPDIR/func -search_refresh
			echo true > $WORKDIR/UPDATE_SOURCELIST
			;;
		pmusicbrowse_expand:*)
			SOURCE=${SOURCE#*:} #remove pmusicbrowse_expand:
#			case $SOURCE in *.pmu|*.m3u|*.pls) . $APPDIR/func_add -check_source;; esac #is it where db points?
			$APPDIR/func -playlist_expand "$SOURCE"
			echo true > $WORKDIR/UPDATE_SOURCELIST
			;;
		pmusicbrowse_collapse:*)
			TMP=${SOURCE#*:} #remove pmusicbrowse_collapse:
			$APPDIR/func -playlist_collapse "$TMP"
			echo true > $WORKDIR/UPDATE_SOURCELIST
			;;
		pmusicbrowse_parent:*)
			IFS=: read C1 PARENT SOURCE <<< "$SOURCE"
			;;
		pmusicbrowse_favorites)
			$APPDIR/func_favorites -show_favorites
			echo true > $WORKDIR/UPDATE_SOURCELIST
			;;
		pmusicbrowse_radio:*)
			grep "|${SOURCE#*:}" "$STORAGE_DIR/index_radio" | cut -d'|' -f1-2 > $WORKDIR/tmp_radio
			awk -F'\n' '{print $1 "|||||||||||||gtk-audio_url"}' $WORKDIR/tmp_radio > $WORKDIR/sourcelist #give it an icon in sourcelist
			$APPDIR/func -add_to_history "pMusic: $(gettext 'Radio stations')" & #update history
			echo true > $WORKDIR/UPDATE_SOURCELIST
			;;
		pmusicbrowse_jamendo_top100:*)
			echo "|$(gettext 'Connecting to') jamendo.com..." > $WORKDIR/sourcelist
			$APPDIR/func_jamendo -jamendo_top100 "${SOURCE#*:}" &
			echo true > $WORKDIR/UPDATE_SOURCELIST
			;;
		pmusicbrowse_podcast_genre:*) #look inside podcast genre
			grep "|${SOURCE#*:}|" "$STORAGE_DIR/index_podcast" > $WORKDIR/sourcelist
			$APPDIR/func -add_to_history "pMusic: Podcast $SOURCE" & #update history
			echo true > $WORKDIR/UPDATE_SOURCELIST
			;;
		pmusicbrowse_podcast:*) #look inside podcast channel
			$APPDIR/func_podcast -expand_channel ${SOURCE#*:}
			echo true > $WORKDIR/UPDATE_SOURCELIST
			;;
	esac
	#---
	if [ -d "${SOURCE}" ]; then
		#define parent directory.
		if [ "$PARENT" ]; then
			echo "$PARENT|..|||||||||||||gtk-go-back" > $WORKDIR/sourcelist
		else
			TMP="`dirname "$SOURCE"`"
			[ "$SOURCE" = ".." ] && SOURCE="$TMP"
			[ "$SOURCE" != "/" ] && echo "$TMP|..|||||||||||||gtk-go-up" > $WORKDIR/sourcelist || echo -n > $WORKDIR/sourcelist
		fi
		#---
		echo "$SOURCE" > $WORKDIR/filebrowser_dir #remember path for next time
		find -L "$SOURCE" -mindepth 1 -maxdepth 1 -printf "%f_test%p|%f||||%TY %Tm/%Td %TH:%TM||||||||%p|gtk-%Y%f\n" \
		| sort -t'|' -k15,15 \
		| sed \
		-e 's/gtk-d.*$/gtk-directory/g' \
		-e 's/gtk-f.*\.pmd$/gtk-audio_playlist_favorites/g' \
		-e 's/gtk-f.*.pmu$\|gtk-f.*.pls$\|gtk-f.*.m3u$\|gtk-f.*.asx$/gtk-audio_playlist/g' \
		-e 's/gtk-f.*$/gtk-audio/g' \
		-e "s/^.*pmu_test\|^.*m3u_test\|^.*pls_test\|^.*pmd_test/pmusicbrowse_expand:/g" \
		-e "s/^.*_test//g" \
		| grep -iE "${AUDIO_FORMATS//$/\\|}|\.pmu\||\.pmd\||\.m3u\||\.pls\||\.asx\||gtk-directory" \
		| grep -vF '|.' \
		>> $WORKDIR/sourcelist
		#---
		[ -f $WORKDIR/gui_is_running ] && echo true > $WORKDIR/UPDATE_SOURCELIST
		case $* in *history*) false;; *) $APPDIR/func -add_to_history "$SOURCE" & ;; esac #update history
	fi
	;;

-set_gtk)
	#GTK-theme
	[ -f $APPDIR/themes/$THEME/gtkrc_mainwindow ] && TMP=":$APPDIR/themes/$THEME/gtkrc_mainwindow"
	[[ "$2" = "menu" && -f $APPDIR/themes/$THEME/gtkrc_rightclick_menu ]] && TMP1=":$APPDIR/themes/$THEME/gtkrc_rightclick_menu"
	#include gtk code for svg-headings
	echo 'pixmap_path "'$WORKDIR'"
		style "svgHeadingImg" { bg_pixmap[NORMAL] = "heading.svg" }
		widget "*svgheading" style "svgHeadingImg"
		style "svgSplashImg" { bg_pixmap[NORMAL] = "splash.svg" }
		widget "*svgsplash" style "svgSplashImg"' > $WORKDIR/svg_gtkrc
	if [ "`grep -F 'ONLY_THIS_GTKTHEME=true' $APPDIR/themes/$THEME/themerc 2>> $STDERR`" ]; then
		export GTK2_RC_FILES="$TMP:$WORKDIR/svg_gtkrc:$APPDIR/themes/$THEME/gtkrc:$TMP1"
	else
		export GTK2_RC_FILES="$HOME/.gtkrc-2.0:$TMP:$WORKDIR/svg_gtkrc:$APPDIR/themes/$THEME/gtkrc:$TMP1"
	fi
	;;

-reset_gtk) #the pMusic specific gtk-theme is not meant for all kinds of dialogs...
	if [ -f "$APPDIR/themes/$THEME/gtkrc" ]; then
		if [ "`grep -F 'THEME_ALL_DIALOGS=false' $APPDIR/themes/$THEME/themerc 2>> $STDERR`" ]; then 
			export GTK2_RC_FILES="`grep -m 1 gtkrc $HOME/.gtkrc-2.0 | cut -d'\"' -f2 2>> $STDERR`:$WORKDIR/svg_gtkrc" #get active theme
		else
			. $APPDIR/func -set_gtk
		fi
	fi
	;;

-plugins)
	find $APPDIR/plugins/ | grep -vE "rc$|/$" > $WORKDIR/tmp
	while read I; do
		. "${I}.rc" #read plugin info from rc file
		XML_PLUGINS=$XML_PLUGINS'
		<vbox>
		<hbox>
		 <pixmap width-request="90" height-request="90" space-expand="false" space-fill="false"><input file>'$PLUGIN_IMAGE'</input><height>80</height></pixmap>
		 <vbox>
		  <text height-request="5"><label>""</label></text>
		  <hbox>
		   <text space-expand="false" space-fill="false" use-markup="true"><label>"<b>'$PLUGIN_NAME'</b>"</label></text>
		   <text space-expand="true" space-fill="true"><label>""</label></text>
		  </hbox>
		  <hbox>
		   <text space-expand="false" space-fill="false"><label>'$PLUGIN_DESCRIPTION'</label></text>
		   <text space-expand="true" space-fill="true"><label>""</label></text>
		  </hbox>
		 </vbox>
		 <text space-expand="true" space-fill="true"><label>""</label></text>
		 <vbox>
		  <button>
		   <label>'$(gettext 'Uninstall')'</label>
		   <input file stock="gtk-clear"></input>
		   <action>rm '$I'; rm '$I'.rc</action>
		   <action>disable:'$PLUGIN_EXEC'</action>
		  </button>'
		   if [ $PLUGIN_RUN_AT_START = true ]; then
		    XML_PLUGINS=$XML_PLUGINS'
		    <text use-markup="true"><label>"<i>'$(gettext 'Runs at startup')'</i>"</label></text>'
		   else
		    XML_PLUGINS=$XML_PLUGINS'
		    <button>
		     <label>'$(gettext 'Run now')'</label>
		     <input file stock="gtk-execute"></input>
		     <action>exec '$APPDIR'/plugins/'$PLUGIN_EXEC' &</action>
		    </button>'
		   fi
		  XML_PLUGINS=$XML_PLUGINS'
		 </vbox>
		 <variable>'$PLUGIN_EXEC'</variable>
		</hbox>
		<hseparator></hseparator>
		</vbox>'
	done < $WORKDIR/tmp

	echo '
<window title="pMusic - '$(gettext 'Plugins')'" icon-name="pmusic" default_width="470" default_height="400">
<vbox>
 '"$($APPDIR/func_svg -heading "$(gettext 'Installed plugins')")"'
 <vbox scrollable="true" spacing="0" width="600">
   '$XML_PLUGINS'
 </vbox>
 <hbox>
  <button>
   <label>'$(gettext 'Check new Plugins')'</label>
   <input file stock="gtk-go-down"></input>
   <action>EXIT:install</action>
  </button>
  <button ok></button>
 </hbox>
</vbox>
</window>' > $WORKDIR/xml_pmusic_plugins
	[ $TOOLTIPS = false ] && sed -i 's%tooltip-%tooltipXXX%g' $WORKDIR/xml_pmusic_plugins #deactivate tooltips
	I=$IFS; IFS=""
	for STATEMENTS in $($GTKDIALOG -f $WORKDIR/xml_pmusic_plugins); do
		eval $STATEMENTS
	done
	IFS=$I
	case $EXIT in
		install)
			export GTK2_RC_FILES="`grep -Fm1 gtkrc $HOME/.gtkrc-2.0 | cut -d'\"' -f2 2>> $STDERR`" #use global gtk-theme for browser
			$BROWSER "$PLUGIN_URL" &
			;;
	esac
	;;

-add_to_history)
	if [ ! "`tail -n 1 "$STORAGE_DIR/index_history" | grep "|    $2$"`" ]; then
		DATO=`date +%s`
		echo "$DATO|pmusic_history:$DATO|    $2" >> "$STORAGE_DIR/index_history"
		cp $WORKDIR/sourcelist "$STORAGE_DIR"/history_files/$DATO
		cp $WORKDIR/tmp_search_albumart "$STORAGE_DIR"/history_files/${DATO}_albumart 2>> $STDERR
		rm -f $WORKDIR/history #reset undo/redo function
		#keep 100 history items 
		ls -1 "$STORAGE_DIR"/history_files > $WORKDIR/tmp_history
		if [ `cat $WORKDIR/tmp_history | wc -l` -gt 200 ]; then
			while read I; do
				rm -f "$STORAGE_DIR"/history_files/$I
			done <<< "$(head -n -200 $WORKDIR/tmp_history)"

			tail -n 100 "$STORAGE_DIR/index_history" > $WORKDIR/tmp_history
			mv -f $WORKDIR/tmp_history "$STORAGE_DIR/index_history"
		fi
	fi
	;;

-history_undo)
	read HISTORY_NR < $WORKDIR/history
	[ ! -s $WORKDIR/history ] && IFS='|' read HISTORY_NR <<< "`tail -n1 "$STORAGE_DIR/index_history"`" #first undo-click: grab last active search/browse
	[ "`head -n1 "$STORAGE_DIR/index_history" | cut -d'|' -f1`" = "$HISTORY_NR" ] && exit #last entry
	SEARCH="`grep -FB1 "$HISTORY_NR" "$STORAGE_DIR/index_history" | cut -d'|' -f3 | head -n1 | cut -c 5-`"
	echo "$SEARCH" > $WORKDIR/filebrowser_dir
	TMP="`grep -FB1 "$HISTORY_NR" "$STORAGE_DIR/index_history" | cut -d'|' -f1 | head -n1`" 
	echo "$TMP" > $WORKDIR/history
	cp -f "$STORAGE_DIR"/history_files/$TMP $WORKDIR/sourcelist 
	#update albumart
	cp -f "$STORAGE_DIR"/history_files/${TMP}_albumart $WORKDIR/tmp_search_albumart
	$APPDIR/func -search_albumart_update
	;;

-history_redo)
	read HISTORY_NR < $WORKDIR/history
	[ ! "$HISTORY_NR" ] && exit
	[ "`tail -n 1 "$STORAGE_DIR/index_history" | cut -d'|' -f1`" = "$HISTORY_NR" ] && exit
	SEARCH="`grep -FA1 "$HISTORY_NR" "$STORAGE_DIR/index_history" | cut -d'|' -f3 | tail -n1 | cut -c 5-`" 
	echo "$SEARCH" > $WORKDIR/filebrowser_dir
	TMP="`grep -FA1 "$HISTORY_NR" "$STORAGE_DIR/index_history" | cut -d'|' -f1 | tail -n1`" 
	echo "$TMP" > $WORKDIR/history
	cp -f "$STORAGE_DIR"/history_files/$TMP $WORKDIR/sourcelist 
	#update albumart
	cp -f "$STORAGE_DIR"/history_files/${TMP}_albumart $WORKDIR/tmp_search_albumart
	$APPDIR/func -search_albumart_update
	;;

-jump_to_time) #start song with given time
	. $APPDIR/func -reset_gtk
	#can't jump in a radio-stream
	read TMP < $WORKDIR/input_type
	if [[ ${TMP} = *radio* ]]; then
		TXT1="$(gettext 'You can not jump in a radio stream.')"
		. $APPDIR/box_ok
		exit
	fi
	FRAME="$(gettext 'Jump to time')"; IMG=""; TXT1="$(gettext 'Jump in song to time'):"; DEFAULT='0:00'
	. $APPDIR/box_input
	if [ $EXIT = "ok" ]; then
		case $INPUT in
			*:*)
				MIN=${INPUT%:*}
				SEC=${INPUT#*:}
				[ ! $SEC ] && SEC=0
				;;
			*)
				MIN=0
				SEC=$INPUT
				;;
		esac
		echo "$[($MIN*60)+$SEC]" > $WORKDIR/SS
		$APPDIR/func_kill -audio
		$APPDIR/func_player -playing -skip_update &
	fi
	;;

-help)
	export GTK2_RC_FILES="`grep -m 1 gtkrc $HOME/.gtkrc-2.0 | cut -d'\"' -f2 2>> $STDERR`" #use global gtk-theme for browser
	$BROWSER http://www.puppylinux.org/wikka/pmusicDoc &
	;;

-statusbar_playlist)
	#calculate length by sum up columns
	MIN=`cut -d'|' -f2 $WORKDIR/playlist | awk -F: '{ SUM += $1} END { print SUM*60 }'`
	SEC=`cut -d'|' -f2 $WORKDIR/playlist | awk -F: '{ SUM += $2} END { print SUM }'`
	if [ ! "$SEC" ]; then #if list is empty
		SEC_TOTAL=00; MIN_TOTAL=0
	else
		MIN_TOTAL=$((($MIN+$SEC)/60))
		SEC_TOTAL=$((($MIN+$SEC)-($MIN_TOTAL*60)))
		[ ${#SEC_TOTAL} -eq 1 ] && SEC_TOTAL="0$SEC_TOTAL" #ensure 2 digits
	fi
	#---
	echo " (${MIN_TOTAL}:${SEC_TOTAL})" > $WORKDIR/statusbar_playlist
	;;

-radio)
	#check if db exists
	if [  ! -s "$STORAGE_DIR/index_radio" ]; then
		echo -e "pmusic_radio|$(gettext 'Missing index')|||||||||||||gtk-info\npmusic_radio|$(gettext 'Doubleclick here to setup')" > $WORKDIR/sourcelist
		echo true > $WORKDIR/UPDATE_SOURCELIST
		exit
	fi
	#---
 	if [ "$2" = "-genre" ]; then
		cat $APPDIR/radio-tags | sed 's%$%|||||||||||||gtk-bullet%g' > $WORKDIR/sourcelist
		$APPDIR/func -add_to_history "pMusic: $(gettext 'Radio Genre')" & #update history
	elif [ "$2" = "-country" ]; then
		cat $APPDIR/radio-country | sed 's%$%|||||||||||||gtk-bullet%g' > $WORKDIR/sourcelist
		$APPDIR/func -add_to_history "pMusic: $(gettext 'Radio Country')" & #update history
	fi
 	echo true > $WORKDIR/UPDATE_SOURCELIST #update source-list
	;;

-playlist_mouse_press)
	case $BUTTON in
	3) #button right-click
		$APPDIR/menu_playqueue
		echo -n > $WORKDIR/RIGHT_MENU
		;;
	2) #button mid-click
		$APPDIR/func -remove_from_list
		;;
	esac
	;;

-playlist_mouse_release)
	IFS='|' read C1 C2 C3 PLAYLIST C < $WORKDIR/PLAYLIST_PRESS_EVENT
	case $BUTTON in
	1)
		if [ "$PLAYLIST" ]; then
			#avoid rating for playing track
			[ "`LC_ALL=C grep -F aplay <<< $(LC_ALL=C ps -eo pid,s,command)`" ] && echo true > $WORKDIR/NO_RATING #playing
			#---
			echo 0 > $WORKDIR/SS
			$APPDIR/func_player -stop -skip_update
			$APPDIR/func_player -playing "$PLAYLIST" &
			exit 0
		fi
		;;
	esac
	;;

-remove_from_list)
	if [ "$PLAYLIST" ]; then
		( flock -e 201
			grep -v "$PLAYLIST" $WORKDIR/playlist > $WORKDIR/tmp_remove_from_list
			mv -f $WORKDIR/tmp_remove_from_list $WORKDIR/playlist
		) 201>$WORKDIR/playlist.lockfile 
		$APPDIR/func -statusbar_playlist & #update statusbar
	fi
	;;

-about)
	. $APPDIR/func -reset_gtk
	. $APPDIR/gui_about "$2"
	$GTKDIALOG -p pmusic_about
	;;

-undo)
	$APPDIR/func_store_playlist
	( flock -e 201
		echo > $WORKDIR/last_added_playlist
		read PLAYLIST_NAME < $WORKDIR/PLAYLIST_NAME
		[ ! "$PLAYLIST_NAME" ] && PLAYLIST_NAME="`ls "$STORAGE_DIR/storage_playlist/" | tail -n1`"
		[ -s $WORKDIR/playlist ] && PLAYLIST_NAME="`ls "$STORAGE_DIR/storage_playlist/" | grep -xB1 "$PLAYLIST_NAME" | head -n1`"
		cp "$STORAGE_DIR/storage_playlist/$PLAYLIST_NAME" $WORKDIR/playlist
		echo "$PLAYLIST_NAME" > $WORKDIR/PLAYLIST_NAME
	) 201>$WORKDIR/playlist.lockfile 
	$APPDIR/func -statusbar_playlist & #update statusbar
	;;

-redo)
	( flock -e 201
		echo > $WORKDIR/last_added_playlist
		read PLAYLIST_NAME < $WORKDIR/PLAYLIST_NAME
		TMP="`ls "$STORAGE_DIR/storage_playlist/" | grep -xA1 "$PLAYLIST_NAME" | tail -n1`"
		cp "$STORAGE_DIR/storage_playlist/$TMP" $WORKDIR/playlist
		echo "$TMP" > $WORKDIR/PLAYLIST_NAME
		$APPDIR/func -statusbar_playlist & #update statusbar
	) 201>$WORKDIR/playlist.lockfile 
	;;

-burn)
	cut -d '|' -f 4 $WORKDIR/playlist | grep -vF "('\|cdda:\|://\|')" > $WORKDIR/tmp_burn #do not include CD tracks and streams
	export BROWSER_DIR=""
	pburn -i $WORKDIR/tmp_burn -m audio
	;;

-show_location)
	[ ! "$2" ] && exit
	SOURCE=${2%/*}
	if type rox > /dev/null 2>&1; then
		rox -d "$SOURCE" &
	else
		echo true > $WORKDIR/UPDATE_SOURCELIST
		. $0 -browse
		echo true > $WORKDIR/UPDATE_SOURCELIST
	fi
	;;

-quit)
	export LC_ALL=C
	echo > $WORKDIR/last_added_playlist #this is what shows up in the save-dialog
	echo 0 > $WORKDIR/maingui_notebook_page #be sure to close message in case of a pMusic restart.
	#first quit guis
	TMP="$(ps -eo pid,command)"
	PS=$(grep -iE "pmusic|aplay|ffplay" <<< "$TMP")
	for I in `grep -F gtkdialog <<< "$PS" | grep -vF radiohits | awk '{print $1}' 2>> $STDERR`; do kill -9 $I 2>> $STDERR; done #do not kill radiohits grabber 
	#stop audio
	pmusic -s stop
	rm -f $WORKDIR/gui_is_running #ensure to flag 'no gui'
	#remove play-icon in playlist
	sed -i "s/gtk-media-play//" $WORKDIR/playlist
	#deactivate equalizer
	if [ -f $HOME/.asoundrc.pequalizer ]; then #using include-mechanism
		cat $HOME/.asoundrc | grep -vF '.asoundrc.pequalizer' > $HOME/.asoundrc
	else
		mv -f $HOME/.asoundrc $HOME/.asoundrc.bak 2>> $STDERR
	fi
	#remove temporary cd-audio files
	rm $WORKDIR/*.wav 2>> $STDERR
	rm $WORKDIR/*.inf 2>> $STDERR
	#remove temporary files, some could be big
	rm $WORKDIR/tmp* 2>> $STDERR
	rm $WORKDIR/trackinfo[0-9]* 2>> $STDERR #keep the refreshing trackinfo files
	echo -n > $WORKDIR/statusbar
	#kill the rest - in case something is still running
	for I in `grep -iF plugins <<< "$PS" | awk '{print $1}' 2>> $STDERR`; do kill -9 $I 2>> $STDERR; done
	for I in `grep -F index <<< "$PS" | awk '{print $1}' 2>> $STDERR`; do kill -9 $I 2>> $STDERR; done
	for I in `grep -F aplay <<< "$PS" | awk '{print $1}' 2>> $STDERR`; do kill -9 $I 2>> $STDERR; done
	for I in `grep -F playing <<< "$PS" | awk '{print $1}' 2>> $STDERR`; do kill -9 $I 2>> $STDERR; done
	for I in `grep -F gtkdialog <<< "$PS" | grep -vF radiohits | awk '{print $1}' 2>> $STDERR`; do kill -9 $I 2>> $STDERR; done
	for I in `grep -vF radiohits <<< "$PS" | awk '{print $1}' 2>> $STDERR`; do kill -9 $I 2>> $STDERR; done
	killall cdda2wav 2>> $STDERR
	#reset info about search filters. Next run will use settings from preferences
	rm $WORKDIR/SEARCH_*
	exit 0
	;;

-rename)
	DIR=${2%/*}
	NAME=${2##*/}; NAME=${NAME%.*}
	[ ! -d "$FILE" ] && EXTENSION=${2##*.}
	#box
	FRAME="$(gettext 'Rename source file')"; IMG="convert"; TXT1="$NAME"; DEFAULT="$NAME"
	. $APPDIR/box_input
	if [ $EXIT = "ok" ]; then
		#if no name (use of " in name clears variable)
		if [ ! "$INPUT" ] || [ "`grep -E '\||\\|\"' <<< "$INPUT"`" ]; then
			TXT1="$(gettext 'Filename is empty!
Be aware that use of some special chars (like \"|) in filename clears value.')"
			. $APPDIR/box_ok
			exit
		fi
		INPUT="`sed 's|"|\\\\"|g' <<< "$INPUT"`"
		#check if already exist
		if [ -f "$DIR"/"$INPUT"."$EXTENSION" ]; then
			TXT1="$DIR"/"$INPUT"."$EXTENSION $(gettext 'already exist')"
			. $APPDIR/box_ok
			exit
		fi
		#---
		echo > $WORKDIR/error
		mv "$DIR"/"$NAME"."$EXTENSION" "$DIR"/"$INPUT"."$EXTENSION" 2> $WORKDIR/error

		TXT1=($(<"$WORKDIR/error"))
		if [ -n "$TXT1" ]; then
			. $APPDIR/box_ok
		else #update playlist and index
			#running sed directly gives problems with special chars
			echo '( flock -e 200' > $WORKDIR/exec3
			echo "sed -i \"s%$DIR/$NAME$EXTENSION|${NAME}.$EXTENSION%$DIR/${INPUT}.$EXTENSION|$INPUT$EXTENSION%g\" \"$STORAGE_DIR/index_mymusic\"" >> $WORKDIR/exec3 #in case no metatags is defined in db
			echo "sed -i \"s%$DIR/${NAME}.$EXTENSION%$DIR/${INPUT}.$EXTENSION%g\" \"$STORAGE_DIR/index_mymusic\"" >> $WORKDIR/exec3
			echo ') 200> $WORKDIR/mymusic_db.lockfile' >> $WORKDIR/exec3
			echo "sed -i \"s%$DIR/${NAME}.$EXTENSION%$DIR/${INPUT}.$EXTENSION%g\" \"$STORAGE_DIR/index_recent\"" >> $WORKDIR/exec3
			echo '( flock -e 201' >> $WORKDIR/exec3
			echo "sed -i \"s%${NAME}.$EXTENSION%${INPUT}.$EXTENSION%g\" $WORKDIR/playlist $WORKDIR/PLAYLIST $WORKDIR/PLAYLIST_ALL" >> $WORKDIR/exec3
			echo ') 201> $WORKDIR/playlist.lockfile' >> $WORKDIR/exec3
			echo "sed -i \"s%${NAME}.$EXTENSION|%${INPUT}.$EXTENSION|%g\" $WORKDIR/sourcelist" >> $WORKDIR/exec3 #column 2 - name
			echo "sed -i \"s%$DIR/${NAME}.$EXTENSION%$DIR/${INPUT}.$EXTENSION%g\" $WORKDIR/favorites" >> $WORKDIR/exec3
			sed -i 's/\&/\\\&/g' $WORKDIR/exec3
			chmod 777 $WORKDIR/exec3
			$WORKDIR/exec3
			echo true > $WORKDIR/UPDATE_SOURCELIST
			echo true | tee $WORKDIR/UPDATE_GUI $WORKDIR/UPDATE_PLAYLIST
		fi
	fi
	;;

-copy)
	FILE="$2"
	FRAME="$(gettext 'Copy source file')"; IMG="copy"; TXT1="$FILE"; DEFAULT="$HOME"
	. $APPDIR/box_input
	if [ $EXIT = "ok" ]; then
		while read I; do
			echo > $WORKDIR/error
			cp "$I" "$INPUT/${I##*/}" 2> $WORKDIR/error
			TXT1=($(<"$WORKDIR/error"))
			[ -n "$TXT1" ] && . $APPDIR/box_ok #error
		done <<< "$FILE"
	fi
	;;

-delete)
	DEL="$2"
	FRAME="$(gettext 'Delete source file')"; IMG="clear"; TXT1="$DEL"
	. $APPDIR/box_yesno
	if [ $EXIT = "yes" ]; then
		while read I; do
			rm "$I"
			. $APPDIR/func -remove_from_list
			#recent index
			grep -vF "$I" "$STORAGE_DIR/index_recent" > $WORKDIR/tmp
			mv -f $WORKDIR/tmp "$STORAGE_DIR/index_recent"
			#db
			( flock -e 200
				grep -avF "$I" "$STORAGE_DIR/index_mymusic" > $WORKDIR/tmp
				mv -f $WORKDIR/tmp "$STORAGE_DIR/index_mymusic"
			) 200>$WORKDIR/mymusic_db.lockfile 
			#favorites
			grep -vF "$I" "$STORAGE_DIR/favorites" > $WORKDIR/tmp
			mv -f $WORKDIR/tmp "$STORAGE_DIR/favorites"
			#sourcelist
			$APPDIR/func -playlist_collapse "$I"
			grep -vE ":${I}|^${I}" $WORKDIR/sourcelist > $WORKDIR/tmp
			mv -f $WORKDIR/tmp $WORKDIR/sourcelist
		done <<< "$DEL"
		echo true > $WORKDIR/UPDATE_SOURCELIST
	fi
	;;





-save_test_with_direct_save-file-dialog)
	read ACTIVE_PLAYLIST < $WORKDIR/last_added_playlist
	DIR=${ACTIVE_PLAYLIST%/*}
	[ ! -s $WORKDIR/last_added_playlist ] && echo "$HOME/pMusic_playlist.pmu" > $WORKDIR/last_added_playlist
	#sort extensions so the active comes first
	echo -e "pmu - pMusic $(gettext 'native format')\nm3u - $(gettext 'Supported by most players')\npls - $(gettext 'Shoutcast playlist')\ntxt - $(gettext 'Plain track list')" > $WORKDIR/tmp_save
	case $ACTIVE_PLAYLIST in
		*.m3u)
			echo "m3u - $(gettext 'Supported by most players')" > $WORKDIR/save_formats
			grep -v m3u $WORKDIR/tmp_save >> $WORKDIR/save_formats
			;;
		*.pls)
			echo "pls - $(gettext 'Shoutcast playlist')" > $WORKDIR/save_formats
			grep -v pls $WORKDIR/tmp_save >> $WORKDIR/save_formats
			;;
		*.txt)
			echo "txt - $(gettext 'Plain track list')" > $WORKDIR/save_formats
			grep -v txt $WORKDIR/tmp_save >> $WORKDIR/save_formats
			;;
		*) #pmu
			mv -f $WORKDIR/tmp_save $WORKDIR/save_formats
			;;
	esac
	#define name and path
	dirname "$(<$WORKDIR/last_added_playlist)" > $WORKDIR/savepath
	[[ ! -s $WORKDIR/savepath || $(<$WORKDIR/savepath) = '.' ]] && echo $HOME > $WORKDIR/savepath
	basename "$(<$WORKDIR/last_added_playlist)" > $WORKDIR/savefile
	#---
	export pmusic_save='
	<window title="pMusic - '$(gettext 'Save playlist')'" icon-name="pmusic" default_height="580" default_width="700">
	 <vbox '$ST'>
	  <timer visible="false" milliseconds="true" interval="500">
	   <action condition="command_is_true([[ ${SAVE_FORMAT} = @(*m3u*|*txt*) ]] && echo true)">enable:SAVE_PATH</action>
	   <action condition="command_is_true([[ ${SAVE_FORMAT} = @(*pmu*|*pls*) ]] && echo true)">disable:SAVE_PATH</action>
	   <action>refresh:STATUSBAR</action>
	  </timer>
	  <frame '$(gettext 'Save playlist')'>
	    <entry visible="false">
	     <variable>SAVEPATH</variable>
	     <input file>'$WORKDIR'/savepath</input>
	    </entry>
	    <hbox>
	     <text><label>"'$(gettext 'Name')':  "</label></text>
	     <entry>
	      <variable>SAVEFILE</variable>
	      <input file>'$WORKDIR'/savefile</input>
	      <action signal="activate">exit:ok</action>
	     </entry>
	    </hbox>
	    <text><label>""</label></text>
	    <chooser action="0" create-folders="true" '$ST'>
	     <variable>SAVE_CHOOSER</variable>
	     <default>'$(dirname "$(cat $WORKDIR/last_added_playlist)")'</default>
	     <action signal="button-release-event" condition="command_is_true([[ -f \"$SAVE_CHOOSER\" ]] && echo true)">basename "$SAVE_CHOOSER" > '$WORKDIR'/savefile</action> 
	     <action signal="button-release-event" condition="command_is_true([[ -d \"$SAVE_CHOOSER\" ]] && echo true)">dirname "$SAVE_CHOOSER" > '$WORKDIR'/savepath</action> 
	     <action signal="button-release-event">refresh:SAVEFILE</action>
	     <action signal="button-release-event">refresh:SAVEPATH</action> 
	    </chooser>
	   <vbox '$SF'>
	   <text><label>""</label></text>
	   <checkbox tooltip-text="'$(gettext 'm3u format supports to skip path description. It will instead use the same path as the m3u file itself. This is handy when music files are moving to a new location.')'">
	    <label>'$(gettext 'Include path')'</label>
	    <variable>SAVE_PATH</variable>
	    <input>echo hei</input>
	    <action>echo $SAVE_PATH > '$WORKDIR'/SAVE_PATH</action>
	   </checkbox>
	   <hbox>
	    <text><label>'$(gettext 'Filetype')'</label></text>
	    <comboboxtext>
	     <variable>SAVE_FORMAT</variable>
	     <input file>'$WORKDIR'/save_formats</input>
	     <action condition="command_is_true([[ ${SAVE_FORMAT} = *pmu* ]] && echo true)">echo "${SAVEFILE%.*}.pmu" > '$WORKDIR'/savefile</action>
	     <action condition="command_is_true([[ ${SAVE_FORMAT} = *m3u* ]] && echo true)">echo "${SAVEFILE%.*}.m3u" > '$WORKDIR'/savefile</action>
	     <action condition="command_is_true([[ ${SAVE_FORMAT} = *pls* ]] && echo true)">echo "${SAVEFILE%.*}.pls" > '$WORKDIR'/savefile</action>
	     <action condition="command_is_true([[ ${SAVE_FORMAT} = *txt* ]] && echo true)">echo "${SAVEFILE%.*}.txt" > '$WORKDIR'/savefile</action>
	     <action>refresh:SAVEFILE</action>
	    </comboboxtext>
	   </hbox>
	  </vbox>
	  </frame>
	   
	  <hbox '$SF'>
	   <statusbar has-resize-grip="false" '$ST'>
	    <variable>STATUSBAR</variable>
	    <input>echo "${SAVEPATH}/${SAVEFILE}"</input>
	   </statusbar>
	   <button cancel></button>
	   <button can-default="true" has-default="true">
	    <label>'$(gettext 'Save')'</label>
	    <input file stock="gtk-save"></input>
	    <action type="exit">ok</action>
	   </button>
	   <statusbar width-request="22"></statusbar>
	  </hbox>
	 </vbox>
	</window>'
	I=$IFS; IFS=""
	for STATEMENTS in $($GTKDIALOG -p pmusic_save); do
		eval $STATEMENTS
	done
	IFS=$I
	SAVEFILE="${SAVEPATH}/${SAVEFILE}"
	if [ "$EXIT" = "ok" ]; then
		case $SAVEFILE in
			*.pmu|*.m3u|*.pls|*.txt)
				EXT=${SAVEFILE##*.}
				SAVEFILE=${SAVEFILE%.*}
				;;
			*)
				EXT=${SAVE_FORMAT%% *}
				;;
		esac
		if [ -s "$SAVEFILE".$EXT ]; then #already exist
			IMG=dialog-warning
			FRAME="$(gettext 'Warning')"
			TXT1="<b>$SAVEFILE.$EXT $(gettext 'already exist')</b>"
			TXT2="$(gettext 'Do you want to overwrite existing file?')"
			DEFAULT=yes
			. $APPDIR/box_yesno
			if [ $EXIT = no ]; then 
				echo -n > $WORKDIR/SAVEFILE
				exit
			fi
		fi
		if [ "$SAVEFILE" ]; then
			case $EXT in
				txt)
					echo -n > "$SAVEFILE".txt
					while IFS='|' read C1 C2 C3 ADR C; do
						[[ $SAVE_PATH = false && ${ADR} != @(http*|cdda*) ]] && ADR=${ADR##*/} #remove path of files if choosen in gui
						echo "$ADR" >> "$SAVEFILE".txt
					done < $WORKDIR/playlist
					;;
				m3u)
					#add EXT info which will speed up reading of the playlist (skip length detection)
					echo '#EXTM3U' > "$SAVEFILE".m3u
					while IFS='|' read C1 LENGTH NAME ADR C; do
						LENGTH=$(((10#${LENGTH%:*} * 60) + 10#${LENGTH#*:}))
						[[ $SAVE_PATH = false && ${ADR} != @(http*|cdda*) ]] && ADR=${ADR##*/} #remove path of files if choosen in gui
						echo -e "#EXTINFO:${LENGTH},$NAME\n$ADR" >> "$SAVEFILE".m3u
					done < $WORKDIR/playlist
					;;
				pls)
					#add EXT info which will speed up reading of the playlist (skip length detection)
					COUNT=1
					echo -n -e "[playlist]\nNumberOfEntries=" > "$SAVEFILE".pls
					grep -c ^ $WORKDIR/playlist >> "$SAVEFILE".pls
					while IFS='|' read COL1 LENGTH NAME ADR ADR_ID; do
						LENGTH=$(((10#${LENGTH%:*} * 60) + 10#${LENGTH#*:}))
						echo -e "File${COUNT}=${ADR}\nTitle${COUNT}=${NAME}\nLength${COUNT}=${LENGTH}" >> "$SAVEFILE".pls
						COUNT=$(($COUNT+1))
					done < $WORKDIR/playlist
					;;
				pmu)
					sed 's/gtk-media-play//' $WORKDIR/playlist > "$SAVEFILE".pmu
					;;
			esac
			#---
			echo "$SAVEFILE".$EXT > $WORKDIR/last_added_playlist
			#update index
			NAME=${SAVEFILE##*/}
			if [[ "$SAVEFILE" = *"$STORAGE_DIR/pmu"* ]]; then #if saved to pmu storage we suppose it is a edited pmusic-generated album. 
				ARTIST=${NAME% - *}
				ALBUM=${NAME#* - }
			else
				ARTIST=${NAME}
				ALBUM=''
			fi
			grep -av "^${SAVEFILE}.$EXT|" "$STORAGE_DIR/index_mymusic" > $WORKDIR/tmp_save
			mv -f $WORKDIR/tmp_save "$STORAGE_DIR/index_mymusic"
			( flock -e 202
				echo "${SAVEFILE}.$EXT|$ARTIST||$ALBUM||||||||||${SAVEFILE}.$EXT|gtk-audio_playlist||||||" >> $WORKDIR/mymusic_stack
			) 202>$WORKDIR/mymusic_stack.lockfile
			$APPDIR/func_index -merge_stack
		else
			TXT1="<b>$(gettext 'Target file is not defined')</b>"
			. $APPDIR/box_ok
		fi
	fi
	;;






-save)
	read ACTIVE_PLAYLIST < $WORKDIR/last_added_playlist
	DIR=${ACTIVE_PLAYLIST%/*}
	[ ! -s $WORKDIR/last_added_playlist ] && echo "$HOME/pMusic_playlist.pmu" > $WORKDIR/last_added_playlist
	#sort extensions so the active comes first
	echo -e "pmu - pMusic $(gettext 'native format')\nm3u - $(gettext 'Supported by most players')\npls - $(gettext 'Shoutcast playlist')\ntxt - $(gettext 'Plain track list')" > $WORKDIR/tmp_save
	case $ACTIVE_PLAYLIST in
		*.m3u)
			echo "m3u - $(gettext 'Supported by most players')" > $WORKDIR/save_formats
			grep -v m3u $WORKDIR/tmp_save >> $WORKDIR/save_formats
			;;
		*.pls)
			echo "pls - $(gettext 'Shoutcast playlist')" > $WORKDIR/save_formats
			grep -v pls $WORKDIR/tmp_save >> $WORKDIR/save_formats
			;;
		*.txt)
			echo "txt - $(gettext 'Plain track list')" > $WORKDIR/save_formats
			grep -v txt $WORKDIR/tmp_save >> $WORKDIR/save_formats
			;;
		*) #pmu
			mv -f $WORKDIR/tmp_save $WORKDIR/save_formats
			;;
	esac
	#---
	export pmusic_save='
	<window title="pMusic - '$(gettext 'Save playlist')'" icon-name="pmusic">
	 <vbox>
	  <timer visible="false" milliseconds="true" interval="500">
	   <action condition="command_is_true([[ ${SAVE_FORMAT} = @(*m3u*|*txt*) ]] && echo true)">enable:SAVE_PATH</action>
	   <action condition="command_is_true([[ ${SAVE_FORMAT} = @(*pmu*|*pls*) ]] && echo true)">disable:SAVE_PATH</action>
	  </timer>
	  <frame '$(gettext 'Save playlist')'>
	   <hbox>
	    <text><label>'$(gettext 'File')'</label></text>
	    <entry accept="savefilename" width-request="300" fs-filters="*.pmu|*.m3u|*.pls" fs-folder="'$DIR'" fs-title="pMusic - '$(gettext 'Save playlist')'">
	     <variable>SAVEFILE</variable>
	     <input file>'$WORKDIR'/last_added_playlist</input>
	     <action signal="activate">exit:ok</action>
	    </entry>
	    <button>
	     <input file stock="gtk-open"></input>
	     <action type="fileselect">SAVEFILE</action>
	    </button>
	   </hbox>
	   <checkbox tooltip-text="'$(gettext 'm3u format supports to skip path description. It will instead use the same path as the m3u file itself. This is handy when music files are moving to a new location.')'">
	    <label>'$(gettext 'Include path')'</label>
	    <variable>SAVE_PATH</variable>
	    <input file>'$WORKDIR'/SAVE_PATH</input>
	    <action>echo $SAVE_PATH > '$WORKDIR'/SAVE_PATH</action>
	   </checkbox>
	   <hbox>
	    <text><label>'$(gettext 'Filetype')'</label></text>
	    <comboboxtext>
	     <variable>SAVE_FORMAT</variable>
	     <input file>'$WORKDIR'/save_formats</input>
	     <action condition="command_is_true([[ ${SAVE_FORMAT} = *pmu* ]] && echo true)">echo "${SAVEFILE%.*}.pmu" > '$WORKDIR'/last_added_playlist</action>
	     <action condition="command_is_true([[ ${SAVE_FORMAT} = *m3u* ]] && echo true)">echo "${SAVEFILE%.*}.m3u" > '$WORKDIR'/last_added_playlist</action>
	     <action condition="command_is_true([[ ${SAVE_FORMAT} = *pls* ]] && echo true)">echo "${SAVEFILE%.*}.pls" > '$WORKDIR'/last_added_playlist</action>
	     <action condition="command_is_true([[ ${SAVE_FORMAT} = *txt* ]] && echo true)">echo "${SAVEFILE%.*}.txt" > '$WORKDIR'/last_added_playlist</action>
	     <action>refresh:SAVEFILE</action>
	    </comboboxtext>
	   </hbox>
	  </frame>
	  <hbox>
	   <button cancel></button>
	   <button can-default="true" has-default="true">
	    <label>'$(gettext 'Ok')'</label>
	    <input file stock="gtk-ok"></input>
	    <action type="exit">ok</action>
	   </button>
	  </hbox>
	 </vbox>
	</window>'
	I=$IFS; IFS=""
	for STATEMENTS in $($GTKDIALOG -p pmusic_save); do
		eval $STATEMENTS
	done
	IFS=$I
	SAVEFILE="${SAVEPATH}/${SAVEFILE}"
	if [ "$EXIT" = "ok" ]; then
		case $SAVEFILE in
			*.pmu|*.m3u|*.pls|*.txt)
				EXT=${SAVEFILE##*.}
				SAVEFILE=${SAVEFILE%.*}
				;;
			*)
				EXT=${SAVE_FORMAT%% *}
				;;
		esac
		if [ -s "$SAVEFILE".$EXT ]; then #already exist
			IMG=dialog-warning
			FRAME="$(gettext 'Warning')"
			TXT1="<b>$SAVEFILE.$EXT $(gettext 'already exist')</b>"
			TXT2="$(gettext 'Do you want to overwrite existing file?')"
			DEFAULT=yes
			. $APPDIR/box_yesno
			if [ $EXIT = no ]; then 
				echo -n > $WORKDIR/SAVEFILE
				exit
			fi
		fi
		if [ "$SAVEFILE" ]; then
			case $EXT in
				txt)
					echo -n > "$SAVEFILE".txt
					while IFS='|' read C1 C2 C3 ADR C; do
						[[ $SAVE_PATH = false && ${ADR} != @(http*|cdda*) ]] && ADR=${ADR##*/} #remove path of files if choosen in gui
						echo "$ADR" >> "$SAVEFILE".txt
					done < $WORKDIR/playlist
					;;
				m3u)
					#add EXT info which will speed up reading of the playlist (skip length detection)
					echo '#EXTM3U' > "$SAVEFILE".m3u
					while IFS='|' read C1 LENGTH NAME ADR C; do
						LENGTH=$(((10#${LENGTH%:*} * 60) + 10#${LENGTH#*:}))
						[[ $SAVE_PATH = false && ${ADR} != @(http*|cdda*) ]] && ADR=${ADR##*/} #remove path of files if choosen in gui
						echo -e "#EXTINFO:${LENGTH},$NAME\n$ADR" >> "$SAVEFILE".m3u
					done < $WORKDIR/playlist
					;;
				pls)
					#add EXT info which will speed up reading of the playlist (skip length detection)
					COUNT=1
					echo -n -e "[playlist]\nNumberOfEntries=" > "$SAVEFILE".pls
					grep -c ^ $WORKDIR/playlist >> "$SAVEFILE".pls
					while IFS='|' read COL1 LENGTH NAME ADR ADR_ID; do
						LENGTH=$(((10#${LENGTH%:*} * 60) + 10#${LENGTH#*:}))
						echo -e "File${COUNT}=${ADR}\nTitle${COUNT}=${NAME}\nLength${COUNT}=${LENGTH}" >> "$SAVEFILE".pls
						COUNT=$(($COUNT+1))
					done < $WORKDIR/playlist
					;;
				pmu)
					sed 's/gtk-media-play//' $WORKDIR/playlist > "$SAVEFILE".pmu
					;;
			esac
			#---
			echo "$SAVEFILE".$EXT > $WORKDIR/last_added_playlist
			#update index
			NAME=${SAVEFILE##*/}
			if [[ "$SAVEFILE" = *"$STORAGE_DIR/pmu"* ]]; then #if saved to pmu storage we suppose it is a edited pmusic-generated album. 
				ARTIST=${NAME% - *}
				ALBUM=${NAME#* - }
			else
				ARTIST=${NAME}
				ALBUM=''
			fi
			grep -av "^${SAVEFILE}.$EXT|" "$STORAGE_DIR/index_mymusic" > $WORKDIR/tmp_save
			mv -f $WORKDIR/tmp_save "$STORAGE_DIR/index_mymusic"
			( flock -e 202
				echo "${SAVEFILE}.$EXT|$ARTIST||$ALBUM||||||||||${SAVEFILE}.$EXT|gtk-audio_playlist||||||" >> $WORKDIR/mymusic_stack
			) 202>$WORKDIR/mymusic_stack.lockfile
			$APPDIR/func_index -merge_stack
		else
			TXT1="<b>$(gettext 'Target file is not defined')</b>"
			. $APPDIR/box_ok
		fi
	fi
	;;

-new)
	> $WORKDIR/playlist
	echo > $WORKDIR/last_added_playlist
	$APPDIR/func -statusbar_playlist & #update statusbar
	;;



	
##############      Search      ################

-search)
	kill -9 `LC_ALL=C ps -eo pid,command | grep -F pmusic | grep -F search2 | awk '{print $1}'` 2>> $STDERR #kill ongoing search
	[[ ${SEARCH} !=	*/* ]] && $APPDIR/func -search2 &
	;;
-search2)
	#this is searching while typing -- only use this for local files (speed issue)
	[[ $SEARCH_MYMUSIC = false && $SEARCH_RADIO = false && $SEARCH_JAMENDO = false && $SEARCH_YOUTUBE = false ]] && exit
	#---
	echo "export LC_ALL=C" > $WORKDIR/tmp_exec
	echo -n "cat " >> $WORKDIR/tmp_exec
	[ $SEARCH_MYMUSIC = true ] && echo -n "\"$STORAGE_DIR/index_mymusic\" " >> $WORKDIR/tmp_exec
	[ $SEARCH_RADIO = true ] && echo -n "\"$STORAGE_DIR/index_radio\" " >> $WORKDIR/tmp_exec
	[ $SEARCH_JAMENDO = true ] && echo -n "\"$STORAGE_DIR/index_jamendo\" " >> $WORKDIR/tmp_exec
	I=$IFS; IFS=" "
	for I in $SEARCH; do echo -n "| grep -iF '$I' " >> $WORKDIR/tmp_exec; done
	IFS=$I
	echo -n " > $WORKDIR/tmp_sourcelist" >> $WORKDIR/tmp_exec
	chmod 722 $WORKDIR/tmp_exec
	$WORKDIR/tmp_exec 2>> $STDERR #execute
	echo "$SEARCH" > $WORKDIR/filebrowser_dir #remember searchtext for next keystroke
	#refresh browser field only if small amount of hits
	if [ `grep -c ^ $WORKDIR/tmp_sourcelist` -lt 500 ]; then
		mv $WORKDIR/tmp_sourcelist $WORKDIR/sourcelist
		echo true > $WORKDIR/UPDATE_SOURCELIST
	fi
	;;
-search_refresh) #click enter in search-field.
	case $SEARCH in
		'')
			echo > $WORKDIR/sourcelist
			exit
			;;
		http://*|https://*)
			SOURCE="$SEARCH"
			. $APPDIR/func_add -add
#			echo true > $WORKDIR/UPDATE_GUI
			;;
		/*) #if file --> add to playlist
			if [ -f "$SEARCH" ]; then
				SOURCE="$SEARCH"
				. $APPDIR/func_add -add
#				echo true > $WORKDIR/UPDATE_GUI
			else #browse
				SOURCE="$SEARCH"
				. $APPDIR/func -browse "$*"
			fi
			exit
			;;
		*) #search
			kill -9 `LC_ALL=C ps -eo pid,command | grep pmusic | grep search2 | awk '{print $1}'` #kill ongoing search
			#clicking on an albumart (searched) we send an extra attribute to avoid albumart-update
			if [ "$2" ]; then
				$APPDIR/func -search_sources "$SEARCH" no_albumart
				NO_UPDATE=no_albumart
			else
				$APPDIR/func -search_sources "$SEARCH" no_update
			fi
			mv -f $WORKDIR/search_sources $WORKDIR/sourcelist
			echo "$SEARCH" > $WORKDIR/filebrowser_dir #remember searchtext for next keystroke
			;;
	esac
	#update history
	[ "$NO_UPDATE" != "no_albumart" ] && $APPDIR/func -add_to_history "$SEARCH" & #we don't want to keep info when user click on albumart
	;;
-search_sources) #this is also used to update the content of sourclist (ie. to update tags).
	SEARCH="$2"
	NO_UPDATE="$3" #point result to another target, or udating of sourcelist is done in gui-code to give an imidiate response
	#this seperates searchresults in different groups
	echo > $WORKDIR/tmp_exec
	[ $UTF8 = false ] && echo "export LC_ALL=${LANG%%_*}" >> $WORKDIR/tmp_exec
	echo "echo -n > $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
	#pMusic allows '-' to define what should NOT be in searchresult. We deal with that after the initial search
	SEARCHSTRING="$SEARCH" #for history index...
	NOT_SEARCH="`echo "$SEARCH" | tr ' ' '\n' | grep "^-" | cut -c2- | tr '\n' ' '`"
	SEARCH="`echo "$SEARCHSTRING" | tr ' ' '\n' | grep -v "^-" | tr '\n' ' '`"
	#When in Radio streamer frontend we should only search for radio stations.
	if [[ "$PMUSIC_FRONTEND" = *'/.Radio'* ]]; then
		SEARCH_COLLECTIONS=false
		SEARCH_MYMUSIC=false
		SEARCH_ALBUMART=false
		SEARCH_RADIO=true
		SEARCH_YOUTUBE=false
		SEARCH_JAMENDO=false
		SEARCH_FILES=false
	fi

	#pfilesearch
	if [ $SEARCH_FILES = true ] && type pfilesearch > /dev/null 2>&1; then
		#no heading is necessary if user don't use any of the indexes.
		if [ $SEARCH_MYMUSIC = true ] || [ $SEARCH_COLLECTIONS = true ] || [ $SEARCH_RADIO = true ] || [ $SEARCH_JAMENDO = true ] || [ $SEARCH_YOUTUBE = true ; then
			echo "echo -e '\n|__${SEARCHPATH}__' >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
		fi
		#---
		echo "pfilesearch -bb -f music -c \"${SEARCH// /[AND]}\" -d \"$SEARCHPATH\"" >> $WORKDIR/tmp_exec
		echo 'sort -u --output='$WORKDIR'/tmp3 '$HOME'/.pfilesearch/hits' >> $WORKDIR/tmp_exec
		echo 'paste -d"|" '$WORKDIR'/tmp3 '$WORKDIR'/tmp3 >> '$WORKDIR'/search_sources' >> $WORKDIR/tmp_exec
	fi

	#My music - Local tracks
	#First we search for both tracks and collections (for speed)
	if [ $SEARCH_COLLECTIONS = true ] || [ $SEARCH_MYMUSIC = true ]; then
		echo "find \"$STORAGE_DIR/favorite_lists/\" -type f -printf \"%p|%f||||||||||||%p|gtk-audio_playlist_favorites||||||\n\" > $WORKDIR/tmp_search_fav" >> $WORKDIR/tmp_exec
		echo -n "cat \"$STORAGE_DIR/index_mymusic\" $WORKDIR/tmp_search_fav" >> $WORKDIR/tmp_exec
		for I in $SEARCH; do echo -n '| grep -iF "'${I//\"/\\\"}'" ' >> $WORKDIR/tmp_exec; done
		echo " > $WORKDIR/tmp_search" >> $WORKDIR/tmp_exec
		if [ $SEARCH_COLLECTIONS = true ]; then
			#search inside MyMusic index
			if [ -s "$STORAGE_DIR/index_mymusic" ]; then
				echo "echo -e '\n|__  $(gettext 'M Y   L I S T S')  __' > $WORKDIR/tmp_search_sources" >> $WORKDIR/tmp_exec
				echo "grep -HiE \"\.pmu\||\.pmd\||\.m3u\||\.pls\|\" $WORKDIR/tmp_search | grep -vF \"$STORAGE_DIR/pmu\" > $WORKDIR/tmp_search_sources2" >> $WORKDIR/tmp_exec
				echo "[ -s $WORKDIR/tmp_search_sources2 ] && cat $WORKDIR/tmp_search_sources $WORKDIR/tmp_search_sources2 >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
				#---
				echo "echo -e '\n|__  $(gettext 'A L B U M S')  __' > $WORKDIR/tmp_search_sources" >> $WORKDIR/tmp_exec
				echo "grep -HF \"$STORAGE_DIR/pmu\" $WORKDIR/tmp_search  > $WORKDIR/tmp_search_sources2" >> $WORKDIR/tmp_exec
				echo "[ -s $WORKDIR/tmp_search_sources2 ] && cat $WORKDIR/tmp_search_sources $WORKDIR/tmp_search_sources2 >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
				#---
				echo "sed -i 's%$WORKDIR/tmp_search%pmusicbrowse_expand%g' $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
			fi
		fi
		if [ $SEARCH_MYMUSIC = true ]; then
			#db tracks
			echo "echo -e '\npmusic_index|__  $(gettext 'M Y   T R A C K S')  __' >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
			if [ -s "$STORAGE_DIR/index_mymusic" ]; then
				echo "grep -ivE \"\.pmu\||\.m3u\||\.pls\||\.pmd\|\" $WORKDIR/tmp_search > $WORKDIR/tmp_search_tracks" >> $WORKDIR/tmp_exec
				#update icons and visible rating coloumn in db
				echo "$APPDIR/func_rating -buildlist 1 $WORKDIR/tmp_search_tracks >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
			fi
		fi
	fi

	#album art
	if [ $SEARCH_ALBUMART = true ] && [ "$NO_UPDATE" != "no_albumart" ]; then
		echo "find \"$STORAGE_DIR/albumart/\" -iname \"*${SEARCH%% *}*\" -printf \"%p\n\" > $WORKDIR/tmp_search_albumart1" >> $WORKDIR/tmp_exec
		echo -n "cat $WORKDIR/tmp_search_albumart1" >> $WORKDIR/tmp_exec
		for I in $SEARCH; do TMP="`echo "$I" | sed 's%"%\\\\\"%g'`"; echo -n "| grep -iF \"$TMP\" " >> $WORKDIR/tmp_exec; done
		#pMusic allows '-' to define what should NOT be in searchresult
		if [ "$NOT_SEARCH" ]; then
			for I in $NOT_SEARCH; do TMP="`echo "$I" | sed 's%"%\\\\\"%g'`"; echo -n "| grep -viF \"$TMP\" " >> $WORKDIR/tmp_exec; done
		fi
		#---
		echo " > $WORKDIR/tmp_search_albumart" >> $WORKDIR/tmp_exec
	fi

	#radio
	if [ $SEARCH_RADIO = true ]; then
		echo "echo -e '\npmusic_radio|__  $(gettext 'R A D I O')  __' >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
		if [ -s "$STORAGE_DIR/index_radio" ]; then
			echo -n "awk -F'\\n' '{print \$1 \"|||||||gtk-audio_url\"}' \"$STORAGE_DIR/index_radio\"" >> $WORKDIR/tmp_exec
			for I in $SEARCH; do echo -n '| grep -iF "'${I//\"/\\\"}'" ' >> $WORKDIR/tmp_exec; done
			echo " >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
		else #message
			echo "echo -e \"pmusic_radio|$(gettext 'Missing index')|||||||||||||gtk-info\npmusic_radio|$(gettext 'Doubleclick here to setup')\" >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
		fi
	fi

	#podcast
	if [ $SEARCH_PODCAST = true ]; then
		echo "echo -e '\npmusic_podcast|__  $(gettext 'P O D C A S T')  __' >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
		if [ -s "$STORAGE_DIR/index_podcast" ]; then
			echo -n "cat \"$STORAGE_DIR/index_podcast\" "$STORAGE_DIR"/podcast_channels " >> $WORKDIR/tmp_exec
			for I in $SEARCH; do echo -n '| grep -iF "'${I//\"/\\\"}'" ' >> $WORKDIR/tmp_exec; done
			echo " >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
		else #message
			echo "echo -e \"pmusic_podcast|$(gettext 'Missing index')|||||||||||||gtk-info\npmusic_podcast|$(gettext 'Doubleclick here to setup')\" >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
		fi
	fi

	#lyrics - does not support free search. Searches for the given phrase
	if [ $SEARCH_LYRICS = true ]; then
		echo "echo -e '\n|__  L Y R I C S  __' >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
		echo "cd \"$STORAGE_DIR\"/lyrics; grep -iFl '$2' ./* | cut -d '/' -f2 | cut -d'.' -f1 > $WORKDIR/search_sources_lyrics" >> $WORKDIR/tmp_exec
		echo "awk -F'\\n' '{print \"pmusicbrowse_search:\" \$1 \"|\" \$1 \"|\"}' $WORKDIR/search_sources_lyrics >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
	fi

	#jamendo.com
	if [ $SEARCH_JAMENDO = true ]; then
		echo "echo -e '\npmusic_jamendo_setup|__  J A M E N D O  __' >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
		#search youtube

		if [ -s "$STORAGE_DIR/index_jamendo" ]; then
			echo -n "cut -c 2- \"$STORAGE_DIR/index_jamendo\"" >> $WORKDIR/tmp_exec
			for I in $SEARCH; do echo -n '| grep -iF "'${I//\"/\\\"}'" ' >> $WORKDIR/tmp_exec; done
			#jamendo index is shrinked with a cut down url. We need to expand URL
			echo " | awk -F \"|\" '{print \"http://api.jamendo.com/get2/stream/track/redirect/?streamencoding=mp31&id=\"\$1\"|\"\$2\"|\"\$3\"|\"\$4\"|\"\$5\"|\"\$6\"|\"\$7\"|\"\$8\"|\"\$9\"|\"\$10\"|\"\$11\"|\"\$12 }' >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
		else #if no indexes is present - search jamendo.com
		
			echo "echo -e \"|$(gettext 'Missing index limits search')\n|    - $(gettext 'Much SLOWER')\n|    - $(gettext 'No multitag search')\n|    - $(gettext 'Max results is 500 pr search')\n|$(gettext 'See Setup in Music-sources menu')\" >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
			echo "wget -t 1 --connect-timeout=1 -O - \"http://api.jamendo.com/get2/id+artist_name+name+album_name+numalbum+dates+genre+duration/track/plain/track_album+album_artist/?searchquery=${SEARCH// /+}&order=searchweight_desc&n=500\" | tr '\t' '|' | sed -e 's/http:/  96      /g' -e 's/Array//g' -e 's/^/http:\/\/api.jamendo.com\/get2\/stream\/track\/redirect\/?streamencoding=mp31\&id=/g' > $WORKDIR/tmp_wget" >> $WORKDIR/tmp_exec
			echo "if grep -F http: $WORKDIR/tmp_wget; then cat $WORKDIR/tmp_wget >> $WORKDIR/search_sources; echo >> $WORKDIR/search_sources; fi" >> $WORKDIR/tmp_exec
		fi
	fi

	#youtube.com
	if [ $SEARCH_YOUTUBE = true ]; then
		echo "echo -e '\n|__  Y O U T U B E  __' >> $WORKDIR/search_sources" >> $WORKDIR/tmp_exec
		echo "$APPDIR/func -search_youtube \"$SEARCH\" &" >> $WORKDIR/tmp_exec
	fi


	#remove first empty lines
	echo "head -n 1001 $WORKDIR/search_sources | tac | head -n-1 | tac > $WORKDIR/tmp_search_sources" >> $WORKDIR/tmp_exec
	#execute
	chmod 722 $WORKDIR/tmp_exec
	$WORKDIR/tmp_exec
	#pMusic allows '-' to define what should NOT be in searchresult
	if [ "$NOT_SEARCH" ]; then
		cp -f $WORKDIR/tmp_search_sources $WORKDIR/tmp
		for I in $NOT_SEARCH; do
			grep -viF "$I" $WORKDIR/tmp > $WORKDIR/tmp2
			mv -f $WORKDIR/tmp2 $WORKDIR/tmp
		done
		mv -f $WORKDIR/tmp $WORKDIR/tmp_search_sources
	fi
	#show only the first 1000 hits
	NR=1000 #max_view
	if [ `grep -c ^ $WORKDIR/tmp_search_sources` -ge $NR ]; then
		echo -e "|$(gettext 'More than') $NR $(gettext 'hits')|||||||||||||gtk-info\n|$(gettext 'Please narrow search')\n" > $WORKDIR/search_sources
		head -n $NR $WORKDIR/tmp_search_sources >> $WORKDIR/search_sources
	else
		mv -f $WORKDIR/tmp_search_sources $WORKDIR/search_sources
	fi
	#here ends the ordinay search.

	#add to playlist if only one hit
	TMP="`grep -F '/' $WORKDIR/search_sources`"
	if [[ ${TMP} != *$'\n'* ]]; then
		SOURCE=${TMP%%|*}
		if [ ! "$(grep -F "${SOURCE#*:}" $WORKDIR/playlist)" ]; then
			. $APPDIR/func_add -add
#			echo true > $WORKDIR/UPDATE_GUI
		fi
	fi
	#update pics for albumart search
	if [ $SEARCH_ALBUMART = true ] && [ "$NO_UPDATE" != "no_albumart" ]; then
		$APPDIR/func -search_albumart_update
	fi
	#now this function is used only to update content in sourcelist. This is possible because search history is stored in index_history
	#see ie. id3io -write
	if [ "$NO_UPDATE" != "no_update" ]; then
		mv -f $WORKDIR/search_sources $WORKDIR/sourcelist
		echo true > $WORKDIR/UPDATE_SOURCELIST
	fi
	;;
-search_albumart_update)
	read ALBUMART_SEARCH_NR < $WORKDIR/albumart_search_NR #how many thumbs should be shown - set in /gui_add
	read START_NR < $WORKDIR/albumart_search_START_NR
	TOTAL=`grep -c ^ $WORKDIR/tmp_search_albumart`
	#are we navigating in album-arts
	case $2 in
		prev)
			if [ $(($START_NR-1)) -gt $ALBUMART_SEARCH_NR ]; then
				START_NR=$(($START_NR-$ALBUMART_SEARCH_NR-1))
				ICON_LEFT=icon_go_left
			else
				START_NR=0
				ICON_LEFT=blank
			fi
			ICON_RIGHT=icon_go_right
			;;
		next)
			START_NR=$(($START_NR+$ALBUMART_SEARCH_NR+1))
			[ $START_NR -gt $TOTAL ] && exit
			ICON_LEFT=icon_go_left
			ICON_RIGHT=icon_go_right
			;;
		*)
			START_NR=0
			ICON_LEFT=blank
			ln -sf $APPDIR/themes/$THEME/blank.svg $WORKDIR/albumart_search_prev.svg
			[[ $ALBUMART_SEARCH_NR -ge $TOTAL || -z $WORKDIR/tmp_search_albumart ]] && ICON_RIGHT=blank || ICON_RIGHT=icon_go_right
			;;
	esac
	echo $START_NR > $WORKDIR/albumart_search_START_NR
	#---
	rm $WORKDIR/albumart_search*.jpg
	COUNT=0
	NR=1
	IFS=$'\n'
	while read I in; do
		#define arrow-buttons
		COUNT=$(($COUNT+1))
		[ $COUNT -lt $START_NR ] && continue
		[ $COUNT = $TOTAL ] && ICON_RIGHT=blank
		#check if pic exist
		[ ! -f "$I" ] && I="`find "$STORAGE_DIR"/albumart -iname "${I##*/}" -printf "%p\n" | head -n1`" #accept chars/capitals
		[ ! -f "$I" ] && continue
		#---
		ln -sf "$I" $WORKDIR/albumart_search$NR.jpg
		NR=$(($NR+1))
		[ $NR -gt $ALBUMART_SEARCH_NR ] && break
	done < $WORKDIR/tmp_search_albumart
	ln -sf $APPDIR/themes/$THEME/$ICON_LEFT.svg $WORKDIR/albumart_search_prev.svg
	ln -sf $APPDIR/themes/$THEME/$ICON_RIGHT.svg $WORKDIR/albumart_search_next.svg
	;;
-pfilesearch)
	#check if pFilesearch is installed
	if ! type pfilesearch > /dev/null 2>&1; then
		TXT1="<b>pFilesearch</b> $(gettext 'is not installed')"
		. $APPDIR/box_ok
		exit
	fi
	#---
	pfilesearch -bb -f music -d "$SEARCHPATH"
	sort -u --output=$WORKDIR/tmp $HOME/.pfilesearch/hits
	paste -d'|' $WORKDIR/tmp $WORKDIR/tmp > $WORKDIR/sourcelist
	echo true > $WORKDIR/UPDATE_SOURCELIST
	;;
-search_youtube) #search youtube is slow, so we run this in background to show indexed quickly
	wget -O - -t 1 -U "$USERAGENT" "http://google.com/search?q=YouTube $2 music" | sed -e 's/http:/\nhttp:/g' -e 's/ - <b>YouTube/\n - <b>YouTube/g' -e 's/href/\nhref/g' | grep -A5 -B3 -F 'http://img.youtube.com/vi/' > $WORKDIR/tmp_ytsearch
	grep -F 'http://img.youtube.com/vi/' $WORKDIR/tmp_ytsearch | cut -d'/' -f5 > $WORKDIR/tmp_ytsearch_id
	grep -F -B1 ' <b>YouTube' $WORKDIR/tmp_ytsearch | grep -F 'href="/url?q=https://www.youtube.com' | cut -d'"' -f3 | cut -c2- | sed -e 's#</b>##g' -e 's#<b>##g' > $WORKDIR/tmp_ytsearch1
	sed -f $APPDIR/sed_html2txt -i $WORKDIR/tmp_ytsearch1
	paste -d'|' $WORKDIR/tmp_ytsearch_id $WORKDIR/tmp_ytsearch1 | awk -F "|" '{print "https://www.youtube.com/watch?v="$1"|"$2"|||||||||128|||https://www.youtube.com/watch?v="$1"|gtk-audio_youtube|" }' >> $WORKDIR/sourcelist
	echo true > $WORKDIR/UPDATE_SOURCELIST
	;;


##############       Misc        #################

-index_recent)
	tail -n 1000 "$STORAGE_DIR/index_recent" > $WORKDIR/tmp_index #keep only last 1000
	tac $WORKDIR/tmp_index > $WORKDIR/sourcelist
	mv -f $WORKDIR/tmp_index "$STORAGE_DIR/index_recent"
	$APPDIR/func -add_to_history "pMusic: $(gettext 'Recent played')" & #update history
	;;

-index_history)
	tail -n 100 "$STORAGE_DIR/index_history" > $WORKDIR/tmp_index #keep only last 100
	tac $WORKDIR/tmp_index | cut -d '|' -f2- > $WORKDIR/sourcelist #reverse list to get last item on top
	mv -f $WORKDIR/tmp_index "$STORAGE_DIR/index_history"
	$APPDIR/func -add_to_history "pMusic: $(gettext 'History')" & #update history
	;;

-info_IWantMusic)
	HEADING="$(gettext 'I want music')"
	IMG='info'
	FRAME="$(gettext 'info')"
	TXT1="$(gettext 'In addition to be an audioplayer and music manager, pMusic is also a tool to build up your own local music collection. This includes music, podcasts, radio programs, lyrics, album art and album playlists.

In the Music-Source menu, you will find different ways to access music. One of the sources is the Radio Grabber that records a radio station and splits the music tracks into different files with correct naming. More info there...

Jamendo.com is a website for free music, and is available via pMusic. It contains a huge amount of music; freely available for you. pMusic also supports searching for music on Youtube. When playing such a track, you are offered the option to download it.

When it comes to lyrics, album art and album playlists, these are downloaded while playing a track. pMusic can store them to a given directory. This is set in the preferences.

A local storage is recommended for snapiness. Lyrics and album art will work ok without a local storage, but not Album playlists. pMusic will search through your music collection and put together songs belonging to each album. These album playlists (and their tracks) will be available when searching, and in the track info window.

<b>Disclaimer</b>: Depending on your home country, these features could have legal issues. The pMusic authors have no responsibility for illegal usage of any kind.')"
	. $APPDIR/box_ok &
	;;

esac
